<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ page import="edu.zhku.web4.pojo.User" %>
<%@ page import="edu.zhku.web4.common.Constants" %>
<%@ page import="java.util.List" %>
<%@ page import="java.util.ArrayList" %>
<%@ page import="java.sql.Connection" %>
<%@ page import="java.sql.Statement" %>
<%@ page import="java.sql.ResultSet" %>
<%@ page import="java.sql.SQLException" %>
<%@ page import="edu.zhku.web4.util.JdbcUtil" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>首页</title>
    <link rel="stylesheet" href="${pageContext.request.contextPath}/layui/css/layui.css">
    <script src="${pageContext.request.contextPath}/layui/layui.js"></script>
    <style>
        .layui-input {
            width: 300px;
            display: inline-block;
        }

        .hide-tip {
            display: none;
        }

        .error-tip {
            color: #FF5722;
        }
    </style>
</head>
<body>
<%
    User user = (User) session.getAttribute(Constants.USER_SESSION_ID);
    if (user != null) {
        request.setAttribute("user", user);
    } else {
        request.removeAttribute("user");
        response.sendRedirect(request.getContextPath() + "/login.jsp");
    }
%>
<ul class="layui-nav" lay-filter="">
    <li class="layui-nav-item layui-this"><a href="${pageContext.request.contextPath}/index.jsp">首页</a></li>
    <li class="layui-nav-item layui-layout-right"><a href="${pageContext.request.contextPath}/logout.jsp">退出登录</a></li>
</ul>
<%
    List<User> list = new ArrayList<>();
    Connection conn = JdbcUtil.getConnection();
    String keyWord = request.getParameter("s");
    String sql = "SELECT * FROM user";
    if (keyWord != null && !"".equals(keyWord)) {
        sql += " WHERE username LIKE '%" + keyWord + "%'";
    }
    try {
        Statement ps = conn.createStatement();
        ResultSet rs = ps.executeQuery(sql);
        while (rs.next()) {
            Long userId = rs.getLong("id");
            String name = rs.getString("username");
            String password = rs.getString("password");
            Integer age = rs.getInt("age");

            list.add(new User(userId, name, password, age));
        }
        rs.close();
        ps.close();
        conn.close();
    } catch (SQLException e) {
        e.printStackTrace();
    }
    request.setAttribute("userList", list);
%>
<div class="layui-container">
    <input type="text" id="key-word" placeholder="输入用户名进行搜索" value="${pageContext.request.getParameter("s")}"
           autocomplete="off" class="layui-input search-input">
    <a class="layui-btn" onclick="handleSearch()">搜索</a>
    <a class="layui-btn" style="float:right" onclick="handleAdd()">添加用户</a>
    <span id="update-msg" style="float:right;line-height: 38px"><b>${updateMsg}&nbsp;</b></span>
    <table class="layui-table" lay-skin="line">
        <colgroup>
            <col width="200">
            <col width="200">
            <col width="200">
            <col width="200">
            <col>
        </colgroup>
        <thead>
        <tr>
            <th>ID</th>
            <th>用户名</th>
            <th>密码</th>
            <th>年龄</th>
            <th>操作</th>
        </tr>
        </thead>
        <tbody>
        <c:forEach items="${userList}" var="u">
            <tr>
                <td>${u.id}</td>
                <td>${u.username}</td>
                <td>******</td>
                <td>${u.age}</td>
                <td>
                    <c:if test="${user.id.equals(u.id)}">
                        <a class="layui-btn layui-btn-xs" onclick="handleEdit('${u.id}', '${u.username}', '${u.password}', '${u.age}')">编辑</a>
                        <a class="layui-btn layui-btn-danger layui-btn-xs" onclick="handleDelete(${u.id})">删除</a>
                    </c:if>
                    <c:if test="${!user.id.equals(u.id)}">
                        <a class="layui-btn layui-btn-disabled layui-btn-xs" onclick="handleEdit('${u.id}', '${u.username}', '${u.password}', '${u.age}')">编辑</a>
                        <a class="layui-btn layui-btn-disabled layui-btn-xs" onclick="handleDelete(${u.id})">删除</a>
                    </c:if>
                </td>
            </tr>
        </c:forEach>
        </tbody>
    </table>
</div>
</body>
<script>

    window.onload = function () {
        setTimeout(() => document.getElementById("update-msg").innerHTML = "<b> </b>", 3000);
    };

    function hideTip(id) {
        document.getElementById(id).className = "hide-tip";
    }

    function errorTip(id) {
        document.getElementById(id).className = "error-tip";
    }

    function checkUsername() {
        const username = document.getElementById("username-input").value;
        if (/^.{2,10}$/.test(username)) {
            hideTip("username-tip");
            return true;
        } else {
            errorTip("username-tip");
            return false;
        }
    }

    function checkPwd1() {
        const pwd1 = document.getElementById("pwd1-input").value;
        if (/^.{6,8}$/.test(pwd1) && pwd1 !== document.getElementById("username-input").value) {
            hideTip("pwd1-tip");
            return true;
        } else {
            errorTip("pwd1-tip");
            return false;
        }
    }

    function checkPwd2() {
        const pwd2 = document.getElementById("pwd2-input").value;
        if (pwd2 === document.getElementById("pwd1-input").value) {
            hideTip("pwd2-tip");
            return true;
        } else {
            errorTip("pwd2-tip");
            return false;
        }
    }

    function checkAge() {
        const ageInputDOM = document.getElementById("age-input");
        if ("" === ageInputDOM.value) {
            errorTip("age-tip");
            return false;
        } else {
            ageInputDOM.value = Math.floor(ageInputDOM.value);
            hideTip("age-tip");
            return true;
        }
    }

    function checkSubmit() {
        return checkUsername() && checkPwd1() && checkPwd2() && checkAge();
    }

    function handleAdd() {
        layer.open({
            title: '添加用户',
            area: '650px',
            btn: [],
            content: `
                <form action="<%=request.getContextPath()%>/add-user.jsp" onsubmit="return checkSubmit()" method="post">
                    <div class="layui-form-item">
                        <label class="layui-form-label">用户名：</label>
                        <input type="text" name="username" id="username-input" class="layui-input" onblur="checkUsername()">
                        <span class="hide-tip" id="username-tip">2-10位</span>
                    </div>
                    <div class="layui-form-item">
                        <label class="layui-form-label">密码：</label>
                        <input type="password" name="pwd1" id="pwd1-input" class="layui-input" onblur="checkPwd1()">
                        <span class="hide-tip" id="pwd1-tip">6-8位，不能与用户名相同</span>
                    </div>
                    <div class="layui-form-item">
                        <label class="layui-form-label">确认密码：</label>
                        <input type="password" name="pwd2" id="pwd2-input" class="layui-input" onblur="checkPwd2()">
                        <span class="hide-tip" id="pwd2-tip">需与密码相同</span>
                    </div>
                    <div class="layui-form-item">
                        <label class="layui-form-label">年龄：</label>
                        <input type="number" name="age" id="age-input" class="layui-input" step="1" min="1" max="130" onblur="checkAge()">
                        <span class="hide-tip" id="age-tip">请输入年龄</span>
                    </div>
                    <div class="layui-form-item">
                        <div class="layui-input-block">
                            <button class="layui-btn" lay-submit lay-filter="formDemo">确认添加</button>
                        </div>
                    </div>
                </form>
                `
        });
    }

    function handleDelete(id) {
        if (confirm(`确认要删除该用户？`)) {
            location.href = "${pageContext.request.contextPath}/delete-user.jsp?id=" + id;
        }
    }

    function handleSearch() {
        const keyWord = document.getElementById("key-word").value;
        if ("" !== keyWord) {
            location.href = "${pageContext.request.contextPath}/index.jsp?s=" + keyWord;
        } else {
            location.href = "${pageContext.request.contextPath}/index.jsp";
        }
    }

    function handleEdit(id, username, password, age) {
        layer.open({
            title: '编辑用户',
            area: '650px',
            btn: [],
            content: `
                <form action="<%=request.getContextPath()%>/edit-user.jsp" onsubmit="return checkSubmit()" method="post">
                    <input type="hidden" name="id" value="` + id + `">
                    <div class="layui-form-item">
                        <label class="layui-form-label">用户名：</label>
                        <input type="text" name="username" id="username-input" value="` + username + `" class="layui-input" onblur="checkUsername()">
                        <span class="hide-tip" id="username-tip">2-10位</span>
                    </div>
                    <div class="layui-form-item">
                        <label class="layui-form-label">密码：</label>
                        <input type="password" name="pwd1" id="pwd1-input" value="` + password + `" class="layui-input" onblur="checkPwd1()">
                        <span class="hide-tip" id="pwd1-tip">6-8位，不能与用户名相同</span>
                    </div>
                    <div class="layui-form-item">
                        <label class="layui-form-label">确认密码：</label>
                        <input type="password" name="pwd2" id="pwd2-input" value="` + password + `" class="layui-input" onblur="checkPwd2()">
                        <span class="hide-tip" id="pwd2-tip">需与密码相同</span>
                    </div>
                    <div class="layui-form-item">
                        <label class="layui-form-label">年龄：</label>
                        <input type="number" name="age" id="age-input" value="` + age + `" class="layui-input" step="1" min="1" max="130" onblur="checkAge()">
                        <span class="hide-tip" id="age-tip">请输入年龄</span>
                    </div>
                    <div class="layui-form-item">
                        <div class="layui-input-block">
                            <button class="layui-btn" lay-submit lay-filter="formDemo">确认修改</button>
                        </div>
                    </div>
                </form>
                `
        });
    }
</script>
</html>
